package kr.hkit.xmlhandler.dom;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class PersonParser {
	private final String TAG_PERSON = "person";
	private final String TAG_NAME = "name";
	private final String TAG_COMPANY = "company";
	private final String ATTR_ID = "id";
	
	private DocumentBuilderFactory factory;
	private DocumentBuilder builder;
	private Document doc;
	
	public PersonParser() throws ParserConfigurationException {
		factory = DocumentBuilderFactory.newInstance();
		builder = factory.newDocumentBuilder();
	}
	
	public ArrayList<PersonValue> parse(String filePath){
		ArrayList<PersonValue> rt = new ArrayList<PersonValue>();
		
		if (filePath == null || "".equals(filePath)) return rt;
		
		try {
			doc = builder.parse(filePath);
			NodeList nodeList = doc.getElementsByTagName(this.TAG_PERSON);
			int lenNodeList = nodeList.getLength();
			for(int i=0; i<lenNodeList; i++){
				PersonValue personVo = new PersonValue();
				Node node = nodeList.item(i);
				if (node.hasAttributes()){
					NamedNodeMap attrMap = node.getAttributes();
					int lenAttrLen = attrMap.getLength();
					for(int j=0 ; j<lenAttrLen; j++){
						Node attrNode = attrMap.item(j);
						if (this.ATTR_ID.equals(attrNode.getNodeName())){
							personVo.setId(Long.parseLong(attrNode.getNodeValue()));
							break;
						}
					}
				}
				
				if (node.hasChildNodes()){
					NodeList childNodeList = node.getChildNodes();
					int lenChildNode = childNodeList.getLength();
					for(int j=0; j<lenChildNode; j++){
						Node childNode = childNodeList.item(j);
						if (this.TAG_NAME.equals(childNode.getNodeName())){
							personVo.setName(childNode.getFirstChild().getNodeValue());
						}else if (this.TAG_COMPANY.equals(childNode.getNodeName())){
							personVo.setCompany(childNode.getFirstChild().getNodeValue());
						}else{
							continue;
						}
					}
				}
				
				rt.add(personVo);
			}
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return rt;
	}
}
